package com.jiangyao.service.impl;

import ch.qos.logback.core.util.TimeUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jiangyao.common.ApiResult;
import com.jiangyao.common.exception.ServerException;
import com.jiangyao.common.utils.FtpClient;
import com.jiangyao.common.utils.StringUtils;
import com.jiangyao.dao.*;
import com.jiangyao.model.dto.*;
import com.jiangyao.model.dto.backend.ChapterCoursewareDTO;
import com.jiangyao.model.dto.backend.ChapterItemDTO;
import com.jiangyao.model.dto.backend.SubjectChapterDTO;
import com.jiangyao.model.dto.backend.SubjectChapterDelDTO;
import com.jiangyao.model.dto.backend.SubjectDTO;
import com.jiangyao.model.dto.backend.SubjectListPageDTO;
import com.jiangyao.model.entity.*;
import com.jiangyao.model.vo.*;
import com.jiangyao.model.vo.backend.ChapterItemVO;
import com.jiangyao.model.vo.backend.SubjectChapterVO;
import com.jiangyao.model.vo.backend.SubjectDetailVO;
import com.jiangyao.model.vo.backend.SubjectListVO;
import com.jiangyao.service.CategoryService;
import com.jiangyao.service.IntegralLogService;
import com.jiangyao.service.SubjectService;
import org.dozer.DozerBeanMapper;
import org.ehcache.core.util.CollectionUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 课程 服务实现类
 * </p>
 *
 * @author lijing
 * @since 2020-08-12
 */
@Service
public class SubjectServiceImpl<getCommentList> extends BaseServiceImpl<ISubjectDao, Subject> implements SubjectService {




    @Autowired
    private DozerBeanMapper dozerBeanMapper;

    @Autowired
    private IProgressDetailDao iProgressDetailDao;

    @Autowired
    private IChapterDao iChapterDao;

    @Autowired
    private ICategoryDao icategoryDao;

    @Autowired
    private IChapterCoursewareDao iChapterCoursewareDao;

    @Autowired
    private ISubjectDao subjectDao;

    @Autowired
    private ISubjectDataDao subjectDataDao;

    @Autowired
    private ICollectDao iCollectDao;

    @Autowired
    private ICoursewareDao iCoursewareDao;

    @Autowired
    private IClassSubjectDao iClassSubjectDao;

    @Autowired
    private IProgressDao iProgressDao;

    @Autowired
    private IEvaluationDao iEvaluationDao;

    @Autowired
    private IUserDao iUserDao;

    @Autowired
    private ISubjectDataDao iSubjectDataDao;

    @Autowired
    private IIntegralLogDao iIntegralLogDao;

    @Autowired
    private IntegralLogService integralLogService;

    @Autowired
    private IPublicProgressDao publicProgressDao;

    @Override
    public SubjectVo getSubjectInfo(SubjectDto subjectDto){
        QueryWrapper<Subject> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("subject_id", subjectDto.getSubjectId());
        queryWrapper.last(" LIMIT 1");
        Subject subject = this.getOne(queryWrapper);
        if (subject == null) {
            throw new ServerException(100, "没有该课程");
        }
        subjectDto.setUserId(getLoginApiUserId());
        SubjectVo subjectVo = dozerBeanMapper.map(subject, SubjectVo.class);
        subjectVo.setClsubId(subjectDto.getClsubId());
        ChapterCourseware chapterCourseware = iProgressDetailDao.getCoursewareName(subjectDto);
        if(chapterCourseware!=null){
            subjectVo.setCoursewareId(chapterCourseware.getCoursewareId());
            subjectVo.setCoursewareAlias(chapterCourseware.getCoursewareAlias());
            subjectVo.setChcoId(chapterCourseware.getChcoId());
        }
        subjectVo.setCover(FtpClient.fullFtpUrl(subjectVo.getCover()));

        QueryWrapper<Collect> collectQueryWrapper=new QueryWrapper<>();
        collectQueryWrapper.eq("type",3);
        collectQueryWrapper.eq("relate_id",subjectDto.getClsubId());
        Integer count = iCollectDao.selectCount(collectQueryWrapper);
        subjectVo.setLikeNum(count);

        QueryWrapper<SubjectData> subjectDataQueryWrapper=new QueryWrapper<>();
        subjectDataQueryWrapper.eq("subject_id",subjectDto.getSubjectId());
        SubjectData subjectData;
        subjectData = iSubjectDataDao.selectOne(subjectDataQueryWrapper);
        if(subjectData!=null){
            subjectVo.setViewNum(subjectData.getViewNum());
        }
        return subjectVo;
    }

    @Override
    public SChapterVo getDirectoryInfo(SubjectDto subjectDto){

        subjectDto.setUserId(getLoginApiUserId());

        SChapterVo sChapterVo=new SChapterVo();
        sChapterVo.setClsubId(subjectDto.getClsubId());
        List<ChapterVo> chapterAndCourseware = iChapterDao.getChapterAndCourseware(subjectDto);
        sChapterVo.setChapterVoList(chapterAndCourseware);
        return sChapterVo;
    }

    @Override
    public ChapterQuestionVo getQuestionsList(SubjectDto subjectDto){


        Integer userId=getLoginApiUserId();

        ChapterQuestionVo chapterQuestionVo=new ChapterQuestionVo();

        chapterQuestionVo.setClsubId(subjectDto.getClsubId());
        /**
         * 获取课件
         */
        List<QuestionVo> coursewareQuestion = iChapterCoursewareDao.getCoursewareQuestion(subjectDto);
        if(coursewareQuestion!=null){
            chapterQuestionVo.setCoursewareQuestionList(coursewareQuestion);
        }

        for (QuestionVo questionVo:coursewareQuestion
             ) {
            QuestionVo coursewareScore = iChapterCoursewareDao.getCoursewareScore(userId, subjectDto.getClsubId(), questionVo.getCoursewareId());
            if(coursewareScore!=null){
                questionVo.setStudyStatus(coursewareScore.getStudyStatus());
            }
        }
        /**
         * 获取章节
         */
        List<QuestionVo> chapterQuestion = iChapterDao.getChapterQuestion(subjectDto);
        if(chapterQuestion!=null){
            chapterQuestionVo.setChapterQuestionList(chapterQuestion);
        }

        for (QuestionVo questionVo:chapterQuestion
             ) {
            QuestionVo chapterScore = iChapterDao.getChapterScore(userId, subjectDto.getClsubId(), questionVo.getChapterId());
            if(chapterScore!=null){
                questionVo.setStudyStatus(chapterScore.getStudyStatus());
            }

        }
        return chapterQuestionVo;
    }

    @Override
    public ChapterCoursewareVo getCoursewareInfo(CoursewareDTO coursewareDTO){
        coursewareDTO.setUserId(getLoginApiUserId());
        ChapterCoursewareVo coursewareInfo = iChapterCoursewareDao.getCoursewareInfo(coursewareDTO);
        if(coursewareInfo==null){
            throw new ServerException(100,"没有该课程详情");
        }
        //查看是否收藏
        QueryWrapper<Collect> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", coursewareDTO.getUserId());
        queryWrapper.eq("relate_id",coursewareDTO.getChcoId());
        queryWrapper.eq("clsub_id",coursewareDTO.getClsubId());
        queryWrapper.eq("type",2);
        Integer isCollect = iCollectDao.selectCount(queryWrapper);

        coursewareInfo.setIsCollect(isCollect>0?1:0);


        //查看当前学期课程的课件数
        Integer integer=iChapterCoursewareDao.getCoursewareCount(coursewareDTO);
        coursewareInfo.setOursewarecNum(integer);
        //获取课程资源路径
        QueryWrapper<Courseware> coursewareQueryWrapper = new QueryWrapper<>();
        coursewareQueryWrapper.eq("courseware_id", coursewareInfo.getCoursewareId());
        coursewareQueryWrapper.last(" LIMIT 1");
        Courseware courseware = iCoursewareDao.selectOne(coursewareQueryWrapper);
        if(courseware!=null){
            coursewareInfo.setResourcesPath(FtpClient.fullFtpUrl(courseware.getResourcesPath()));
        }

        return coursewareInfo;
    }

    @Override
    public SChapterCoursewareVo getCoursewareList(CoursewareDTO coursewareDTO){
        List<SimpleChapterCoursewareVo> coursewareList = iChapterCoursewareDao.getCoursewareList(coursewareDTO);
        if(coursewareList.isEmpty()){
            throw new ServerException(100,"没有课程课件列表");
        }
        for (SimpleChapterCoursewareVo coursewareVo:coursewareList){
            QueryWrapper<ProgressDetail> progressDetailQueryWrapper=new QueryWrapper<>();
            progressDetailQueryWrapper.eq("chco_id",coursewareVo.getChcoId());
            Integer num = iProgressDetailDao.selectCount(progressDetailQueryWrapper);

            coursewareVo.setWatchNum(num);

        }

        SChapterCoursewareVo sChapterCoursewareVo = new SChapterCoursewareVo();
        sChapterCoursewareVo.setClsubId(coursewareDTO.getClsubId());
        sChapterCoursewareVo.setSimpleChapterCoursewareVoList(coursewareList);
        return sChapterCoursewareVo;
    }

    @Override
    public Boolean saveCourseware(StudyCoursewareDto studyCoursewareDto){

        ProgressDetail progressDetail = dozerBeanMapper.map(studyCoursewareDto, ProgressDetail.class);

        //更新班级id
        QueryWrapper<ClassSubject> classSubjectQueryWrapper=new QueryWrapper<>();
        classSubjectQueryWrapper.eq("clsub_id",studyCoursewareDto.getClsubId());
        classSubjectQueryWrapper.last(" LIMIT 1");
        ClassSubject classSubject = iClassSubjectDao.selectOne(classSubjectQueryWrapper);
        progressDetail.setClassId(classSubject.getClassId());

        QueryWrapper<ChapterCourseware> chapterCoursewareQueryWrapper=new QueryWrapper<>();
        chapterCoursewareQueryWrapper.eq("chco_id",studyCoursewareDto.getChcoId());
        chapterCoursewareQueryWrapper.last(" LIMIT 1");
        ChapterCourseware chapterCourseware = iChapterCoursewareDao.selectOne(chapterCoursewareQueryWrapper);

        progressDetail.setChapterId(chapterCourseware.getChapterId());
        progressDetail.setCoursewareId(chapterCourseware.getCoursewareId());
        progressDetail.setUserId(getLoginApiUserId());
        //写入progress_detail表数据
        iProgressDetailDao.insert(progressDetail);

        //写入观看次数
        SubjectData subjectData;
        QueryWrapper<SubjectData> subjectDataQueryWrapper=new QueryWrapper<>();
        subjectDataQueryWrapper.eq("subject_id",chapterCourseware.getSubjectId());
        subjectDataQueryWrapper.last("limit 1");
         subjectData = iSubjectDataDao.selectOne(subjectDataQueryWrapper);
        if(subjectData==null){
            SubjectData subjectData1=new SubjectData();
            subjectData1.setSubjectId(chapterCourseware.getSubjectId());
            subjectData1.setViewNum(1);
            iSubjectDataDao.insert(subjectData1);
        }else {
            UpdateWrapper<SubjectData> subjectDataUpdateWrapper = new UpdateWrapper<>();
            subjectDataUpdateWrapper.eq("subject_id", chapterCourseware.getSubjectId());
            subjectDataUpdateWrapper.set("view_num", subjectData.getViewNum() + 1);
            iSubjectDataDao.update(null, subjectDataUpdateWrapper);
        }
        //准备学习时长

        long diff = (studyCoursewareDto.getEndTime().getTime() - studyCoursewareDto.getStartTime().getTime()) / 1000;
        long diffTime=studyCoursewareDto.getStudyTime()>0?studyCoursewareDto.getStudyTime():diff;

        //准备学习进度百分比
        QueryWrapper<Courseware> coursewareQueryWrapper=new QueryWrapper<>();
        coursewareQueryWrapper.eq("courseware_id",chapterCourseware.getCoursewareId());
        coursewareQueryWrapper.last("limit 1");
        Courseware courseware = iCoursewareDao.selectOne(coursewareQueryWrapper);
        double progressPercent = (Math.round(courseware.getTotalTime() / diffTime) / 100.0);

        QueryWrapper<Progress> progressQueryWrapper =new QueryWrapper<>();
        progressQueryWrapper.eq("user_id",getLoginApiUserId());
        progressQueryWrapper.eq("chco_id",studyCoursewareDto.getChcoId());
        progressQueryWrapper.eq("clsub_id",studyCoursewareDto.getClsubId());
        progressQueryWrapper.last("limit 1");
        Progress progress1 = iProgressDao.selectOne(progressQueryWrapper);
        Integer progressCount = iProgressDao.selectCount(progressQueryWrapper);
        Integer status=diffTime>0&&diffTime<courseware.getTotalTime()?1:(diffTime>=courseware.getTotalTime()?2:0);

        if(progressCount==0){
            Progress progress=dozerBeanMapper.map(progressDetail,Progress.class);
            progress.setProgress(diffTime);
            progress.setProgressPercent(progressPercent);
            progress.setStatus(status);
            iProgressDao.insert(progress);
        }else if(progressCount>0&&progress1.getStatus()!=2){
            UpdateWrapper<Progress> updateWrapper=new UpdateWrapper<>();
            updateWrapper.eq("user_id",getLoginApiUserId());
            updateWrapper.eq("chco_id",studyCoursewareDto.getChcoId());
            updateWrapper.eq("clsub_id",studyCoursewareDto.getClsubId());

            updateWrapper.set("progress",diffTime);
            updateWrapper.set("progress_percent",progressPercent);
            updateWrapper.set("status",status);
            iProgressDao.update(null,updateWrapper);
        }

        if(status==2){
            QueryWrapper<Progress> progress2=new QueryWrapper<>();
            progress2.eq("user_id",getLoginApiUserId());
            progress2.eq("chco_id",studyCoursewareDto.getChcoId());
            progress2.eq("clsub_id",studyCoursewareDto.getClsubId());
            progress2.last(" limit 1");
            Progress progress = iProgressDao.selectOne(progress2);

            QueryWrapper<IntegralLog> integralLogQueryWrapper=new QueryWrapper<>();
            integralLogQueryWrapper.eq("user_id",getLoginApiUserId());
            integralLogQueryWrapper.eq("source_id",progress.getId());
            integralLogQueryWrapper.eq("source_type",5);
            integralLogQueryWrapper.eq("status",1);
            Integer count = iIntegralLogDao.selectCount(integralLogQueryWrapper);
            if(count==0){
                IntegralLog integralLog=dozerBeanMapper.map(progress,IntegralLog.class);
                integralLog.setUserId(getLoginApiUserId());
                integralLog.setSourceType(5);
                integralLog.setSourceId(progress.getId().toString());
                integralLog.setIntegralNum(5);
                integralLog.setCreateTime(new Date());
                integralLog.setStatus(1);
                integralLogService.saveLogAndUpdateUserIntegral(true,integralLog);
                //iIntegralLogDao.insert(integralLog);
            }

        }
        return true;

    }

    @Override
    public Page<EvaluationVo> getCommentList(SubjectListPageDto subjectListPageDto){
        Page<EvaluationVo> page=new Page<>(subjectListPageDto.getPageNo(),subjectListPageDto.getPageSize());
        iEvaluationDao.getListPage(page,subjectListPageDto);
        if(CollectionUtils.isEmpty(page.getRecords())){
            return page;
        }

        QueryWrapper<Evaluation> evaluationQueryWrapper =new QueryWrapper<>();
        page.getRecords().forEach(vo->{
            QueryWrapper<User> userQueryWrapper=new QueryWrapper<>();
            userQueryWrapper.eq("user_id",vo.getUserId());
            userQueryWrapper.last("limit 1");
            User user = iUserDao.selectOne(userQueryWrapper);
            if(user!=null){
                vo.setUserName(user.getUserName());
            }

            QueryWrapper<Progress> progressQueryWrapper=new QueryWrapper<>();
            progressQueryWrapper.eq("user_id",vo.getUserId());
            progressQueryWrapper.eq("clsub_id",vo.getClsubId());
            progressQueryWrapper.eq("status",2);
            Integer coursewareNum = iProgressDao.selectCount(progressQueryWrapper);
            vo.setCoursewareNum(coursewareNum);

            List<CommentReplyVo> replayListById = iEvaluationDao.getReplayListById(vo.getId());
            if(!replayListById.isEmpty()){
                for(CommentReplyVo replay:replayListById){
                    QueryWrapper<User> userWrapper=new QueryWrapper<>();
                    userWrapper.eq("user_id",replay.getUserId());
                    userWrapper.last("limit 1");
                    User users = iUserDao.selectOne(userWrapper);
                    if(users!=null){
                        replay.setUserName(users.getUserName());
                    }
                }
                vo.setCommentReplyVoList(replayListById);
            }

        });
        return page;
    }


    @Override
    public Boolean saveComment(EvaluationDto evaluationDto){
        Evaluation evaluation = dozerBeanMapper.map(evaluationDto, Evaluation.class);
        evaluation.setUserId(getLoginApiUserId());
        evaluation.setCreateTime(new Date());
        //业务不明确，默认审核通过
        evaluation.setStatus(1);
        evaluation.setReleteId(0);
        iEvaluationDao.insert(evaluation);
        return true;
    }

    @Override
    public Boolean saveReply(EvaluationDto evaluationDto){
        Evaluation evaluation = dozerBeanMapper.map(evaluationDto, Evaluation.class);
        evaluation.setUserId(getLoginApiUserId());
        evaluation.setCreateTime(new Date());
        //业务不明确，默认审核通过
        evaluation.setStatus(1);
        if(evaluationDto.getReleteId()==0){
            throw new ServerException(100,"回复课程失败，无对应的评论");
        }
        evaluation.setReleteId(evaluationDto.getReleteId());
        evaluation.setType(1);
        iEvaluationDao.insert(evaluation);
        return true;
    }

    @Override
    public Boolean getLike(SubjectDto subjectDto){
        QueryWrapper<Collect> collectQueryWrapper=new QueryWrapper<>();
        collectQueryWrapper.eq("relate_id",subjectDto.getClsubId());
        collectQueryWrapper.eq("user_id",getLoginApiUserId());
        collectQueryWrapper.eq("type",3);
        collectQueryWrapper.eq("action",2);
        Integer count = iCollectDao.selectCount(collectQueryWrapper);
        return  count>0?true:false;
    }

    @Override
    public void editPublicStatus(SubjectDTO subjectDTO) {
        if (CollectionUtils.isEmpty(subjectDTO.getSubjectIdList()) || subjectDTO.getIsPublic() == null) {
            return;
        }
        UpdateWrapper<Subject> updateWrapper = new UpdateWrapper<>();
        updateWrapper.in("subject_id", subjectDTO.getSubjectIdList());
        updateWrapper.set("is_public", subjectDTO.getIsPublic());
        updateWrapper.set("update_time", new Date());
        updateWrapper.set("update_admin_id", getLoginAdminUserId());
        this.update(updateWrapper);
    }


    @Override
    public void editChoiceness(SubjectDTO subjectDTO) {
        if (CollectionUtils.isEmpty(subjectDTO.getSubjectIdList()) || subjectDTO.getIsChoiceness() == null) {
            return;
        }
        UpdateWrapper<Subject> updateWrapper = new UpdateWrapper<>();
        updateWrapper.in("subject_id", subjectDTO.getSubjectIdList());
        updateWrapper.set("is_choiceness", subjectDTO.getIsChoiceness());
        updateWrapper.set("update_time", new Date());
        updateWrapper.set("update_admin_id", getLoginAdminUserId());
        this.update(updateWrapper);
    }

    @Override
    public List getPublicCategory() {
        QueryWrapper<Category> query=new QueryWrapper<>();
        query.eq("type",1).eq("status",1).orderByAsc("sort_order");
        return icategoryDao.selectList(query);
    }

    @Override
    public Page<PublicSubjectListVo> getPublicChoiceness(PublicSubjectDto dto) {
        dto.setIsChoiceness(1);
        Page<PublicSubjectListVo> page = new Page<>(dto.getPageNo(), dto.getPageSize());
        subjectDao.getPublicListPage(page, dto);
        if (CollectionUtils.isEmpty(page.getRecords())) {
            return page;
        }
        page.getRecords().forEach(vo -> {
            if (StringUtils.isNotEmpty(vo.getCover())) {
                vo.setCoverFull(FtpClient.fullFtpUrl(vo.getCover()));
            }
            QueryWrapper<PublicProgress> query=new QueryWrapper<>();
            query.eq("subject_id",vo.getSubjectId());
            vo.setLearnNum(publicProgressDao.selectCount(query));
        });
        return page;
    }

    @Override
    public Page<PublicSubjectListVo> getPublicNewest(PublicSubjectDto dto) {
        Page<PublicSubjectListVo> page = new Page<>(dto.getPageNo(), dto.getPageSize());
        subjectDao.getPublicListPage(page, dto);
        if (CollectionUtils.isEmpty(page.getRecords())) {
            return page;
        }
        page.getRecords().forEach(vo -> {
            if (StringUtils.isNotEmpty(vo.getCover())) {
                vo.setCoverFull(FtpClient.fullFtpUrl(vo.getCover()));
            }
        });
        return page;
    }

    @Override
    public Page<SubjectListVO> getListPage(SubjectListPageDTO listPageDTO) {
        Page<SubjectListVO> page = new Page<>(listPageDTO.getPageNo(), listPageDTO.getPageSize());
        subjectDao.getListPage(page, listPageDTO);
        if (CollectionUtils.isEmpty(page.getRecords())) {
            return page;
        }
        page.getRecords().forEach(vo -> {
            if (StringUtils.isNotEmpty(vo.getCover())) {
                vo.setCoverFull(FtpClient.fullFtpUrl(vo.getCover()));
            }
        });
        return page;
    }

    @Override
    public void add(SubjectDTO subjectDTO) {
        Subject subject = dozerBeanMapper.map(subjectDTO, Subject.class);
        subject.setSubjectId(null);
        subject.setCreateTime(new Date());
        subject.setCreateAdminId(getLoginAdminUserId());
        subject.setStatus(1);
        this.save(subject);
        // 新建课程数据（观看次数等）
        SubjectData subjectData = new SubjectData();
        subjectData.setSubjectId(subject.getSubjectId());
        subjectDataDao.insert(subjectData);
    }

    @Override
    public void edit(SubjectDTO subjectDTO) {
        Subject subject = this.getById(subjectDTO.getSubjectId());
        if (subject == null) {
            throw new ServerException(100, "课程不存在");
        }
        UpdateWrapper<Subject> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("subject_id", subjectDTO.getSubjectId());
        updateWrapper.set("category_id", subjectDTO.getCategoryId());
        updateWrapper.set("subject_name", subjectDTO.getSubjectName());
        updateWrapper.set("lecturer_admin", subjectDTO.getLecturerAdmin());
        updateWrapper.set("subject_desc", subjectDTO.getSubjectDesc());
        updateWrapper.set("subject_detail", subjectDTO.getSubjectDetail());
        updateWrapper.set("cover", subjectDTO.getCover());
        updateWrapper.set("update_time", new Date());
        updateWrapper.set("update_admin_id", getLoginAdminUserId());
        this.update(updateWrapper);
    }

    @Override
    public void editStatus(SubjectDTO subjectDTO) {
        if (CollectionUtils.isEmpty(subjectDTO.getSubjectIdList())) {
            return;
        }
        UpdateWrapper<Subject> updateWrapper = new UpdateWrapper<>();
        updateWrapper.in("subject_id", subjectDTO.getSubjectIdList());
        updateWrapper.set("status", subjectDTO.getStatus() == null ? 1 : subjectDTO.getStatus());
        updateWrapper.set("update_time", new Date());
        updateWrapper.set("update_admin_id", getLoginAdminUserId());
        this.update(updateWrapper);
    }

    @Override
    public SubjectDetailVO getDetail(SubjectDTO subjectDTO) {
        Subject subject = this.getById(subjectDTO.getSubjectId());
        if (subject == null) {
            throw new ServerException(100, "课程不存在");
        }
        SubjectDetailVO subjectVo = dozerBeanMapper.map(subject, SubjectDetailVO.class);
        if (StringUtils.isNotBlank(subjectVo.getCover())) {
            subjectVo.setCoverFull(FtpClient.fullFtpUrl(subjectVo.getCover()));
        }
        return subjectVo;
    }



    @Override
    public SubjectChapterVO getChapterList(SubjectDTO subjectDTO) {
        Subject subject = this.getById(subjectDTO.getSubjectId());
        if (subject == null) {
            throw new ServerException(100, "课程不存在");
        }
        SubjectChapterVO subjectChapterVO =new SubjectChapterVO();
        subjectChapterVO.setSubjectId(subject.getSubjectId());
        subjectChapterVO.setSubjectName(subject.getSubjectName());
        // 获取章节列表 与 章节课件
        List<ChapterItemVO> chapterList =  iChapterDao.getChapterAndCoursewareList(subject.getSubjectId());
        subjectChapterVO.setChapterList(chapterList);
        return subjectChapterVO;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void updateChapter(SubjectChapterDTO subjectChapterDTO) {
        Subject subject = this.getById(subjectChapterDTO.getSubjectId());
        if (subject == null) {
            throw new ServerException(100, "课程不存在");
        }
        if (CollectionUtils.isEmpty(subjectChapterDTO.getChapterList())) {
            return;
        }
        // 编辑章节
        for (ChapterItemDTO chapterItemDTO : subjectChapterDTO.getChapterList()) {
            updateChapterItem(subject.getSubjectId(), chapterItemDTO);
        }
        // 修改课程修改时间
        UpdateWrapper<Subject> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("subject_id", subject.getSubjectId());
        updateWrapper.set("update_time", new Date());
        updateWrapper.set("update_admin_id", getLoginAdminUserId());
        this.update(updateWrapper);
    }

    /**
     * 编辑章节
     *
     * @param subjectId      课件ID
     * @param chapterItemDTO 章节课件DTO
     */
    private void updateChapterItem(Integer subjectId, ChapterItemDTO chapterItemDTO) {
        // 章节ID
        Integer chapterId = chapterItemDTO.getChapterId();
        // 新建章节
        if (chapterId == null || chapterId == 0) {
            Chapter chapter = dozerBeanMapper.map(chapterItemDTO, Chapter.class);
            chapter.setSubjectId(subjectId);
            chapter.setStatus(1);
            chapter.setCreateTime(new Date());
            chapter.setCreateAdminId(getLoginAdminUserId());
            iChapterDao.insert(chapter);
            chapterId = chapter.getChapterId();
        } else {
            // 编辑章节
            UpdateWrapper<Chapter> uw = new UpdateWrapper<>();
            uw.eq("chapter_id", chapterId);
            uw.set("chapter_name", chapterItemDTO.getChapterName());
            uw.set("questions_id", chapterItemDTO.getQuestionsId());
            uw.set("sort_order", chapterItemDTO.getSortOrder());
            iChapterDao.update(null, uw);
        }
        if (CollectionUtils.isEmpty(chapterItemDTO.getCoursewareList())) {
            return;
        }

        // 编辑章节课件
        for (ChapterCoursewareDTO chapterCoursewareDTO : chapterItemDTO.getCoursewareList()) {
            updateChapterCourseware(subjectId, chapterId, chapterCoursewareDTO);
        }

    }

    /**
     * 编辑章节课件
     *
     * @param subjectId     课件ID
     * @param chapterId     章节ID
     * @param coursewareDTO 章节课件DTO
     */
    private void updateChapterCourseware(Integer subjectId, Integer chapterId, ChapterCoursewareDTO coursewareDTO) {
        // 章节课件关联主键ID
        Integer chcoId = coursewareDTO.getChcoId();
        // 新建章节
        if (chcoId == null || chcoId == 0) {
            ChapterCourseware chapterCourseware = dozerBeanMapper.map(coursewareDTO, ChapterCourseware.class);
            chapterCourseware.setSubjectId(subjectId);
            chapterCourseware.setChapterId(chapterId);
            chapterCourseware.setStatus(1);
            chapterCourseware.setCreateTime(new Date());
            chapterCourseware.setCreateAdminId(getLoginAdminUserId());
            iChapterCoursewareDao.insert(chapterCourseware);
            chcoId = chapterCourseware.getChcoId();
        } else {
            // 编辑章节
            UpdateWrapper<ChapterCourseware> uw = new UpdateWrapper<>();
            uw.eq("chco_id", chcoId);
            uw.set("courseware_id", coursewareDTO.getCoursewareId());
            uw.set("courseware_alias", coursewareDTO.getCoursewareAlias());
            uw.set("questions_id", coursewareDTO.getQuestionsId());
            uw.set("sort_order", coursewareDTO.getSortOrder());
            iChapterCoursewareDao.update(null, uw);
        }
    }


    @Override
    public void deleteChapter(SubjectChapterDelDTO delDTO) {
        Subject subject = this.getById(delDTO.getSubjectId());
        if (subject == null) {
            throw new ServerException(100, "课程不存在");
        }
        boolean edit = false;
        // 删除课程章节
        if (delDTO.getChapterId() != null && delDTO.getChapterId() != 0) {
            UpdateWrapper<Chapter> uw = new UpdateWrapper<>();
            uw.eq("chapter_id", delDTO.getChapterId());
            uw.set("status", 0);
            iChapterDao.update(null, uw);
            edit = true;
        }
        // 删除章节课件
        if (delDTO.getChcoId() != null && delDTO.getChcoId() != 0) {
            UpdateWrapper<ChapterCourseware> uw = new UpdateWrapper<>();
            uw.eq("chco_id", delDTO.getChcoId());
            uw.set("status", 0);
            iChapterCoursewareDao.update(null, uw);
            edit = true;
        }
        if (!edit) {
            return;
        }

        // 修改课程修改时间
        UpdateWrapper<Subject> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("subject_id", subject.getSubjectId());
        updateWrapper.set("update_time", new Date());
        updateWrapper.set("update_admin_id", getLoginAdminUserId());
        this.update(updateWrapper);
    }
}
